// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.firebase.gradle.plugins.license;

import com.android.build.gradle.tasks.BundleAar;
import java.io.File;
import org.gradle.api.Plugin;
import org.gradle.api.Project;

/**
 * Interprets the implementation config for the underlying project and generates license artifacts.
 * Gradle configuration phase consists of the following steps:
 *
 * <ul>
 *   <li>Apply the com.jaredsburrows.license plugin onto the project
 *   <li>Defines a generateLicenses task common to java and android projects
 *   <li>Additional licenses may be configured by projects using the {@link
 *       com.google.firebase.gradle.plugins.license.ThirdPartyLicensesExtension}
 * </ul>
 *
 * Execution phase consists of the following steps
 *
 * <ul>
 *   <li>Remote url licenses are deduped and downloaded.
 *   <li>The licenseReleaseReport and licenseReport tasks defined by the com.jaredsburrows.license
 *       plugin are executed for android and java projects respectively.
 *   <li>The license report (json) generated by the com.jaredsburrows.license is used by the {@link
 *       GenerateLicensesTask} to create the artifacts necessary for our release.
 * </ul>
 */
public class LicenseResolverPlugin implements Plugin<Project> {
  private static final String[] ANDROID_PLUGINS = {
    "com.android.application", "com.android.library", "com.android.test"
  };

  @Override
  public void apply(Project project) {
    ThirdPartyLicensesExtension thirdPartyLicenses =
        project.getExtensions().create("thirdPartyLicenses", ThirdPartyLicensesExtension.class);

    project.afterEvaluate(
        it -> {
          if (!isAndroidProject(project)) {
            return;
          }

          File licensesDir =
              new File(
                  String.join(
                      "/",
                      project.getBuildDir().getAbsolutePath(),
                      "generated",
                      "third_party_licenses"));

          GenerateLicensesTask licensesTask =
              project
                  .getTasks()
                  .create(
                      "generateLicenses",
                      GenerateLicensesTask.class,
                      task -> {
                        task.setAdditionalLicenses(thirdPartyLicenses.getLibraries());
                        task.setOutputDir(licensesDir);
                      });

          project
              .getTasks()
              .withType(
                  BundleAar.class,
                  task -> {
                    task.dependsOn(licensesTask);
                    task.from(licensesTask.getOutputDir());
                  });
        });
  }

  private static boolean isAndroidProject(Project project) {
    for (String plugin : ANDROID_PLUGINS) {
      if (project.getPlugins().hasPlugin(plugin)) {
        return true;
      }
    }
    return false;
  }
}
